<script setup lang="ts" name="VehicleTrajectoryMap">
import { loadAmap } from '/@/utils/mapLoad';
import { drawRoute } from '/@/utils/mapUtils';
import { vehicleTrajectoryMapKey } from './provider';

import dayjs from 'dayjs';
// import MapLenged from './MapLenged.vue';

import CameraLengedIcon from './icon/camera-lenged.png';
// import ProjectLengedIcon from './icon/project-lenged.png';
import GarbageLengedIcon from './icon/garbage-lenged.png';
// import LoadLengedIcon from './icon/load-lenged.png';
// import UnloadLengedIcon from './icon/unload-lenged.png';
import CameraMarkerIcon from './icon/camera.png';
// import ProjectMarkerIcon from './icon/project.png';
// import GarbageMarkerIcon from './icon/garbage.png';
import LoadMarkerIcon from './icon/load.png';
import UnloadMarkerIcon from './icon/unload.png';
// 新图标
import MapCar from './icon/map-car.png';
import MapStop from './icon/stop.png';
import MapStopLen from './icon/stop-lenged.png';
// import MapWork from './icon/work.png';
import MapWorkLen from './icon/work_lenged.png';
import MapTrajectory from './icon/trajectory.png';
import MapBayonet from './icon/bayonet.png';
import MapSpeed from './icon/speed.png';
import carIcon from './icon/car.png';
// import { mount } from 'sortablejs';
/**
 * 车辆轨迹地图
 * 图列
 * 聚合点
 * 	不同类型的点弹窗
 * 点标记
 *  轨迹回放
 * 轨迹
 * 摄像头
 * 	抓拍 视频回放
 */

interface PointType {
	lnglat: number[];
}
const props = withDefaults(
	defineProps<{
		kuponoId?: string;
		date?: string[];
		pointData: {
			camera: PointType[]; // 摄像头
			project: PointType[]; // 工地
			garbage: PointType[]; // 消纳
			load: PointType[]; // 装在点
			unload: PointType[]; // 卸载点
			stay: PointType[]; // 停留点位
		};
		pathData: Array<{
			lng: number;
			lat: number;
			time: string;
		}>;
	}>(),
	{},
);

// const emits = defineEmits<{
// 	'camera-marker-click': [data: any];
// }>();

provide(vehicleTrajectoryMapKey, {
	startCarMarkerAnimation,
	pauseCarMarkerAnimation,
	resumeCarMarkerAnimation,
	setCarMovingEvent,
	setCarMovealongEvent,
	setCarMarkerMoveCurrentPosition,
});

let map: any;

onMounted(() => {
	initMap();
	window.popClick = () => {
		let imgBoxA = document.querySelector('.imgBoxA');
		let imgBoxImg = document.querySelector('.imgBoxImg');

		if (indexTxt > 0) {
			indexTxt--;
			imgBoxA.href = imgItem.value?.bayonetImageList[indexTxt].picPath;
			imgBoxImg.src = imgItem.value?.bayonetImageList[indexTxt].picPath;
		} else {
			imgBoxImg.src = imgItem.value?.bayonetImageList[0].picPath;
			imgBoxA.href = imgItem.value?.bayonetImageList[0].picPath;
			indexTxt = 0;
		}
	};
	window.popClicknext = () => {
		let imgBoxA = document.querySelector('.imgBoxA');
		let imgBoxImg = document.querySelector('.imgBoxImg');

		if (imgItem.value?.bayonetImageList.length - 1 > indexTxt) {
			indexTxt++;
			imgBoxA.href = imgItem.value?.bayonetImageList[indexTxt].picPath;
			imgBoxImg.src = imgItem.value?.bayonetImageList[indexTxt].picPath;
		} else {
			imgBoxImg.src =
				imgItem.value?.bayonetImageList[
					imgItem.value?.bayonetImageList.length - 1
				].picPath;
			imgBoxA.href =
				imgItem.value?.bayonetImageList[
					imgItem.value?.bayonetImageList.length - 1
				].picPath;
			indexTxt = 0;
		}
	};
});

onUnmounted(() => {
	if (map) map.destroy();
});

// 事件类型
enum EventType {
	Camera = 'camera',
	Project = 'project',
	Garbage = 'garbage',
	Load = 'load',
	Unload = 'unload',
	Stay = 'stay',
	Path = 'path',
}
const tabPosition = ref('车辆分布');
// 地图初始化
// 车辆marker
let carMarker: any;
// 移动到第几个点
const carMarkerMoveCurrentPosition = ref(0);
// 车辆marker移动事件注入
const carMoveEvent = ref<{
	moving: (
		e: any,
		data: {
			data: {
				lng: number;
				lat: number;
				time: string;
			};
			index: number;
		},
	) => void;
	movealong: () => void;
}>({
	moving: () => {},
	movealong: () => {},
});

// 滑块设置当前播放位置
function setCarMarkerMoveCurrentPosition(time: string) {
	const diffArr: number[] = [];
	props.pathData.forEach((item) => {
		diffArr.push(Math.abs(dayjs(time).diff(dayjs(item.time), 'milliseconds')));
	});

	const index = diffArr.findIndex((item) => item === Math.min(...diffArr));
	carMarkerMoveCurrentPosition.value = index === -1 ? 0 : index;

	carMarker.setPosition([
		props.pathData[carMarkerMoveCurrentPosition.value].lng,
		props.pathData[carMarkerMoveCurrentPosition.value].lat,
	]);
}

// 设置car移动中监听位置
function setCarMovingEvent(cb: (e: any) => void) {
	carMoveEvent.value.moving = cb;
}

// 设置car移动结束监听位置
function setCarMovealongEvent(cb: () => void) {
	carMoveEvent.value.movealong = cb;
}

watch(
	() => [props.pathData, props.pointData],
	() => {
		initMap();
		// drawMarkerCluster();
	},
);

async function initMap() {
	try {
		await loadAmap();
		if (!map) {
			map = new window.AMap.Map('kupono-map-container', {
				zoom: 9,
			});
		}

		map.clearMap();
		// //4、将简易行政区图层添加到地图
		let polygons = [];
		window.AMap.plugin('AMap.DistrictSearch', function () {
			var districtSearch = new window.AMap.DistrictSearch({
				subdistrict: 1, //获取边界不需要返回下级行政区
				extensions: 'all', //返回行政区边界坐标组等具体信息
				level: 'district', //查询行政级别为 市
			});
			//搜索所有省、直辖市信息
			districtSearch.search('成都市', function (status: any, result: any) {
				// console.log(status, result);
				//status：complete 表示查询成功，no_data 为查询无结果，error 代表查询错误
				//查询成功时，result 即为对应的行政区信息
				// console.log(JSON.stringify(result.districtList[0].districtList));
				let districtList: any;
				districtList = result.districtList[0].districtList;
				districtList.forEach((item: any) => {
					districtSearch.search(
						item.name,
						function (status2: any, result2: any) {
							// console.log(status2, result2);
							//status：complete 表示查询成功，no_data 为查询无结果，error 代表查询错误
							//查询成功时，result 即为对应的行政区信息
							var bounds = result2.districtList[0].boundaries; //获取边界信息
							// console.log('bounds', item.name);
							if (bounds) {
								for (var i = 0; i < bounds.length; i++) {
									// bounds[i].strokeColor = getRandomColor();	fillColor: getRandomColor(), //多边形填充颜色
									//生成行政区划 polygon
									var polygon = new window.AMap.Polygon({
										map: map, //显示该覆盖物的地图对象
										strokeWeight: 1, //轮廓线宽度
										path: bounds[i], //多边形轮廓线的节点坐标数组
										fillOpacity: 0.4,
										fillColor: '#1890FF',
										strokeColor: '#EEF4FF', //线条颜色
									});
									polygons.push(polygon);
									map.add(polygons);
									polygon.on('mouseover', function (event: any) {
										if (event.lnglat) {
											polygon.setOptions({
												fillOpacity: 0.1,
												strokeColor: '#CCFFFO',
											});
											// var content = ["<div class='info_box_contant  text-[#f47920]'> " + item.name + '  </div>'];
											// var infoWindow = new window.AMap.InfoWindow({
											// 	isCustom: true, //使用自定义窗体
											// 	content: content.join('<br>'),
											// });
											// infoWindow.open(map, [event.lnglat.lng, event.lnglat.lat]);
										}
									});
									polygon.on('mouseover', function (event: any) {
										if (event.lnglat) {
											var content = [
												"<div class='info_box_contant  text-[#f47920]'> " +
													item.name +
													'  </div>',
											];
											var infoWindow = new window.AMap.InfoWindow({
												isCustom: true, //使用自定义窗体
												content: content.join('<br>'),
											});
											infoWindow.open(map, [
												event.lnglat.lng,
												event.lnglat.lat,
											]);
										}
									});

									polygon.on('mouseout', function (event: any) {
										if (event.lnglat) {
											polygon.setOptions({
												fillOpacity: 0.4,
												fillColor: '#1890FF',
												strokeColor: '#EEF4FF', //线条颜色
											});
											// var content = ""
											// console.log(content)
											var infoWindow = new window.AMap.InfoWindow({
												isCustom: true, //使用自定义窗体
												content: '',
												offset: new window.AMap.Pixel(20, 20),
											});

											infoWindow.open(map, [
												event.lnglat.lng,
												event.lnglat.lat,
											]);
										}
									});
									polygon.on('click', () => {
										infoWindowclose();
									});
								}
								map.on('zoomend', () => {
									if (map) {
										const currentZoom = map.getZoom();
										// console.log(currentZoom, "oooooooooo")
										if (polygons.length) {
											if (currentZoom > 18) {
												polygons.forEach((item) => item.hide());
											} else {
												polygons.forEach((item) => item.show());
											}
										}
									}
								});
							}
						},
					);
				});
			});
		});
		// 绘制路线
		if (props.pathData.length > 0) {
			drawRoute(
				map,
				props.pathData.map((item) => [item.lng, item.lat]),
				'#437AFF',
				true,
				false,
			);

			// 添加起点
			addMarker({
				position: [props.pathData[0].lng, props.pathData[0].lat],
				offset: new window.AMap.Pixel(-8, -8),
				content:
					'<div style="width: 16px;height: 16px;border-radius: 9px;background: #fff;border: 6px solid var(--el-color-primary);"></div>',
			});
			// 添加终点
			addMarker({
				position: [
					props.pathData[props.pathData.length - 1].lng,
					props.pathData[props.pathData.length - 1].lat,
				],
				offset: new window.AMap.Pixel(-8, -8),
				content:
					'<div style="width: 16px;height: 16px;border-radius: 9px;background: #fff;border: 6px solid var(--el-color-primary);"></div>',
			});

			// 绘制车辆
			carMarker = addMarker({
				position: [props.pathData[0].lng, props.pathData[0].lat],
				offset: new window.AMap.Pixel(-40, -30),
				content: markerContent(),
			});

			// marker移动监听
			carMarker.on('moving', function (e: any) {
				// 记录移动到第几个点
				carMarkerMoveCurrentPosition.value = e.passedPath.length;
				carMoveEvent.value.moving(e, {
					data: props.pathData[carMarkerMoveCurrentPosition.value - 1],
					index: carMarkerMoveCurrentPosition.value,
				});
			});

			// marker移动结束监听
			carMarker.on('movealong', function () {
				console.log('移动结束');
				carMarker.stopMove();
				carMarkerMoveCurrentPosition.value = 0;
				carMoveEvent.value.movealong();
			});
		}

		/* map.on("zoomend", () => {
        if (map) {
          const currentZoom = map.getZoom()
          if (currentZoom > 19) {
            console.log(currentZoom, "uuuuuuuu")
          }
        }
      })*/

		map.setFitView();
		// 绘制聚合点
		drawMarkerCluster();

		map.on('click', () => {
			infoWindowclose();
		});

		map.setFitView();
	} catch (err) {
		console.error(err);
	}
}
defineExpose({
	drawMarkerCluster,
	initMap,
	tabsClick,
});
// function getRandomColor() {
// 	let r = Math.floor(Math.random() * 256).toString(16);
// 	let g = Math.floor(Math.random() * 256).toString(16);
// 	let b = Math.floor(Math.random() * 256).toString(16);

// 	// 确保每个数字至少为两位数
// 	if (r.length == 1) r = '0' + r;
// 	if (g.length == 1) g = '0' + g;
// 	if (b.length == 1) b = '0' + b;
// 	// console.log('#' + r + g + b);
// 	return '#' + r + g + b;
// }

/* ------------------ 绘制车辆 ------------------------- */
function addMarker(options: {
	position: number[];
	offset: any;
	content?: string;
}) {
	if (!map) return;

	const marker = new window.AMap.Marker(options);
	map.add(marker);
	return marker;
}

function markerContent() {
	return `
    <div class="box">
      <div class="big"></div>
      <div class="small"></div>
      <div class="car">
        <img src="${MapCar}" />
      </div>
    </div>`;
}

function startCarMarkerAnimation(speed: number, init?: boolean) {
	if (init) carMarkerMoveCurrentPosition.value = 0;
	const pathArr = props.pathData
		.slice(
			carMarkerMoveCurrentPosition.value > props.pathData.length - 3
				? props.pathData.length - 3
				: carMarkerMoveCurrentPosition.value,
		)
		.map((item) => ({
			position: [item.lng, item.lat],
			...item,
		}));
	carMarker.moveAlong(pathArr, {
		// 每一段的时长
		duration: speed, //可根据实际采集时间间隔设置
		// JSAPI2.0 是否延道路自动设置角度在 moveAlong 里设置
		autoRotation: true,
	});
}

function pauseCarMarkerAnimation() {
	carMarker.pauseMove();
}
function resumeCarMarkerAnimation() {
	carMarker.resumeMove();
}

/* ------------------ 点聚合 -------------------------- */
let markerClusterCamera: any;
let markerClusterProject: any;
let markerClusterGarbage: any;
let markerClusterLoad: any;
let markerClusterUnload: any;
let markerClusterStay: any;
// let markerClusterPath: any;
let cameraPoint: PointType[];
let projectPoint: PointType[];
let garbagePoint: PointType[];
let loadPoint: PointType[];
let unloadPoint: PointType[];
let stayPoint: PointType[];
// let pathOter: any[];

// let trajectPoint: PointType[];
function drawMarkerCluster() {
	const cameraLenged = lengeds.value.find((l) => l.type === EventType.Camera);
	const projectLenged = lengeds.value.find((l) => l.type === EventType.Project);
	const garbageLenged = lengeds.value.find((l) => l.type === EventType.Garbage);
	const loadLenged = lengeds.value.find((l) => l.type === EventType.Load);
	const unloadLenged = lengeds.value.find((l) => l.type === EventType.Unload);
	const stayLenged = lengeds.value.find((l) => l.type === EventType.Stay);
	// const PathLenged = lengeds.value.find((l) => l.type === EventType.Path);
	// 摄像头
	if (cameraLenged && cameraLenged.selected) {
		cameraPoint = props.pointData.camera.map((item) => ({
			...item,
			type: EventType.Camera,
			icon: CameraMarkerIcon,
		}));
	} else {
		cameraPoint = [];
	}

	if (!markerClusterCamera) {
		markerClusterCamera = new window.AMap.MarkerCluster(map, cameraPoint, {
			gridSize: 60, // 聚合网格像素大小
			renderClusterMarker: _renderClusterMarker, // 自定义聚合点样式
			renderMarker: _renderMarker, // 自定义非聚合点样式
		});
		markerClusterCamera.on('click', markerClusterClickHandler);
	} else {
		markerClusterCamera.setData(cameraPoint);
	}

	// 工地
	if (projectLenged && projectLenged.selected) {
		projectPoint = props.pointData.project.map((item) => ({
			...item,
			type: EventType.Project,
			icon: carIcon,
		}));
	} else {
		projectPoint = [];
	}

	if (!markerClusterProject) {
		markerClusterProject = new window.AMap.MarkerCluster(map, projectPoint, {
			gridSize: 60, // 聚合网格像素大小
			renderClusterMarker: _renderClusterMarker, // 自定义聚合点样式
			renderMarker: _renderMarker, // 自定义非聚合点样式
		});
		markerClusterProject.on('click', markerClusterClickHandler);
	} else {
		markerClusterProject.setData(projectPoint);
	}

	// 消纳
	if (garbageLenged && garbageLenged.selected) {
		// GarbageMarkerIcon
		garbagePoint = props.pointData.garbage.map((item) => ({
			...item,
			type: EventType.Garbage,
			icon: carIcon,
		}));
	} else {
		garbagePoint = [];
	}

	if (!markerClusterGarbage) {
		markerClusterGarbage = new window.AMap.MarkerCluster(map, garbagePoint, {
			gridSize: 60, // 聚合网格像素大小
			renderClusterMarker: _renderClusterMarker, // 自定义聚合点样式
			renderMarker: _renderMarker, // 自定义非聚合点样式
		});
		markerClusterGarbage.on('click', markerClusterClickHandler);
	} else {
		markerClusterGarbage.setData(garbagePoint);
	}

	// 装载点
	if (loadLenged && loadLenged.selected) {
		loadPoint = props.pointData.load.map((item) => ({
			...item,
			type: EventType.Load,
			icon: LoadMarkerIcon,
		}));
	} else {
		loadPoint = [];
	}
	if (!markerClusterLoad) {
		markerClusterLoad = new window.AMap.MarkerCluster(map, loadPoint, {
			gridSize: 60, // 聚合网格像素大小
			renderClusterMarker: _renderClusterMarker, // 自定义聚合点样式
			renderMarker: _renderMarker, // 自定义非聚合点样式
		});
		markerClusterLoad.on('click', markerClusterClickHandler);
	} else {
		markerClusterLoad.setData(loadPoint);
	}

	// 卸载点
	if (unloadLenged && unloadLenged.selected) {
		unloadPoint = props.pointData.unload.map((item) => ({
			...item,
			type: EventType.Unload,
			icon: UnloadMarkerIcon,
		}));
	} else {
		unloadPoint = [];
	}
	if (!markerClusterUnload) {
		markerClusterUnload = new window.AMap.MarkerCluster(map, unloadPoint, {
			gridSize: 60, // 聚合网格像素大小
			renderClusterMarker: _renderClusterMarker, // 自定义聚合点样式
			renderMarker: _renderMarker, // 自定义非聚合点样式
		});
		markerClusterUnload.on('click', markerClusterClickHandler);
	} else {
		markerClusterUnload.setData(unloadPoint);
	}
	// 轨迹点 markerClusterPath
	// if (PathLenged && PathLenged.selected) {
	// 	trajectPoint = props.pathData.map((item) => ({
	// 		...item,
	// 		type: EventType.Path,
	// 		icon: MapTrajectory,
	// 	}));
	// } else {
	// 	trajectPoint = [];
	// }
	// if (!markerClusterPath) {
	// 	markerClusterPath = new window.AMap.MarkerCluster(map, trajectPoint, {
	// 		gridSize: 10, // 聚合网格像素大小
	// 		renderClusterMarker: _renderClusterMarker, // 自定义聚合点样式
	// 		renderMarker: _renderMarker, // 自定义非聚合点样式
	// 	});
	// 	markerClusterPath.on('click', markerClusterClickHandler);
	// } else {
	// 	markerClusterPath.setData(trajectPoint);
	// }
	// 停留点
	if (stayLenged && stayLenged.selected) {
		stayPoint = props.pointData.stay.map((item) => ({
			...item,
			type: EventType.Stay,
			icon: MapStop,
		}));
	} else {
		stayPoint = [];
	}

	if (!markerClusterStay) {
		markerClusterStay = new window.AMap.MarkerCluster(map, stayPoint, {
			gridSize: 60, // 聚合网格像素大小
			renderClusterMarker: _renderClusterMarker, // 自定义聚合点样式
			renderMarker: _renderMarker, // 自定义非聚合点样式
		});
		markerClusterStay.on('click', markerClusterClickHandler);
	} else {
		markerClusterStay.setData(stayPoint);
	}

	// 绘制连线点
	if (props.pointData.camera.length > 1) {
		// drawRouteMeshLine(
		// 	map,
		// 	props.pointData.camera.map((m) => m.lnglat),
		// 	'#F18506'
		// );
		setLine(
			map,
			props.pointData.camera.map((m) => m.lnglat),
		);
	} else {
		setLine(map, []);
	}

	function markerClusterClickHandler(e: any) {
		if (e.clusterData.length <= 1) return;
		map.setZoom(20);
		map.setCenter([e.clusterData[0].lng, e.clusterData[0].lat]);
	}
}
function setLine(map: any, pointArr: any) {
	for (let i = 0; i < pointArr.length - 1; i++) {
		let arr = [pointArr[i], pointArr[i + 1]];
		excuteFn(map, arr);
	}
	function excuteFn(map: any, points: any) {
		// Container: Loca 的核心控制类，可以控制光源、视角变换、图层渲染等。
		const loca = new Loca.Container({
			map, // 传入地图实例 还可以这样写: map: map (ES6语法)
		});
		// 呼吸点
		// ScatterLayer: 带有动画效果的图层类型，用于展示散点数据，支持动画效果，如呼吸点、闪烁点等。大地面上的点，可展示三种类型：颜色圆、图标、动画图标
		const scatter = new Loca.ScatterLayer({
			// 创建一个散点图层
			loca, // 传入容器实例 (相当于把散点图层添加到地图上)
			zIndex: 10, // 图层层级
			opacity: 0, // 图层透明度
			visible: true, // 图层是否可见
			zooms: [2, 22], // 图层显示的缩放级别范围
		});
		/*
		 * geojson 格式的数据源，一个数据源可以给多个图层同时提供数据。一个geojson数据源可以同时拥有点、线、面的数据类型，每个图层绘制的时候会自动获取 合适的数据类型进行渲染
		 * */
		function dataPoints() {
			let tempData = [];
			for (let i = 0; i < points.length; i++) {
				tempData.push({
					type: 'Feature',
					properties: {
						type: 0,
						ratio: 0.0369,
						lineWidthRatio: 1,
					},
					geometry: {
						type: 'Point',
						coordinates: points[i],
					},
				});
			}
			return {
				type: 'FeatureCollection',
				features: tempData,
			};
		}
		const pointGeo = new Loca.GeoJSONSource({
			// 创建一个 GeoJSON 对象 返回的数据必须是 geojson 格式
			data: dataPoints(),
		});
		scatter.setSource(pointGeo); // 给上面创建的散点图层设置数据源

		// 弧线
		// PulseLinkLayer: 连接飞线图层，可以支持弧度，宽度，过渡色等能力。 并且还支持脉冲动画，可以表达数据的朝向
		const pulseLink = new Loca.PulseLinkLayer({
			// 创建一个弧线图层
			loca,
			zIndex: 10, // 设置图层的层级
			opacity: 1, // 设置图层的透明度
			visible: true, // 设置图层是否可见
			zooms: [2, 22], // 设置图层可见的缩放级别范围
			depth: true, // 设置是否开启深度检测
		});

		// GeoJSONSource: 图层的数据源，可以是本地数据，也可以是远程数据，数据格式必须是 geojson 格式
		function dataLines() {
			let tempData = [];
			for (let i = 0; i < points.length - 1; i++) {
				let start = points[i];
				let end = points[i + 1];
				tempData.push({
					type: 'Feature',
					properties: {
						type: 0,
						ratio: 0.0369,
						lineWidthRatio: 1,
					},
					geometry: {
						type: 'LineString',
						coordinates: [start, end],
					},
				});
			}
			return {
				type: 'FeatureCollection',
				features: tempData,
			};
		}
		const geo = new Loca.GeoJSONSource({
			// 创建一个 GeoJSON 对象
			data: dataLines(),
		});
		pulseLink.setSource(geo); // 给上面的弧线图层设置数据源
		pulseLink.setStyle({
			// 设置样式
			unit: 'meter', // 设置单位为米
			dash: [0, 0], // 设置虚线样式
			lineWidth: function () {
				// 设置线宽
				return [10, 10]; // 设置线宽范围
			},
			height: function (index: any, feat: any) {
				console.log(feat);
				console.log(index);
				// 设置高度
				return feat.distance / 3 + 6; // 设置高度范围
			},
			lineColors: function (index: any, feat: any) {
				console.log(feat);
				console.log(index);
				// 设置线颜色
				return ['rgb(255,0,0)']; // 设置线颜色范围
			},
			maxHeightScale: 0.5, // 弧顶位置比例
			headColor: 'rgba(255, 0, 0, 1)', // 设置头部颜色
			trailColor: 'rgba(255, 0,0,0)', // 设置尾部颜色
		});
		loca.add(pulseLink); // 将图层添加到容器中
	}
}
function _renderClusterMarker(context: any) {
	// 聚合中点个数
	const clusterCount = context.count;
	const div = document.createElement('div');
	div.style.position = 'relative';
	div.style.display = 'flex';
	div.style.alignItems = 'center';
	div.style.justifyContent = 'center';

	// 根据聚合数量计算气泡大小
	const baseSize = 34;
	const size = Math.min(baseSize + clusterCount * 1.5, 70); // 最大不超过70px

	// 创建气泡容器
	const bubble = document.createElement('div');
	bubble.style.width = `${size}px`;
	bubble.style.height = `${size}px`;
	bubble.style.background = '#1890ff';
	bubble.style.border = '2px solid #FFFFFF';
	bubble.style.borderRadius = '50%';
	bubble.style.display = 'flex';
	bubble.style.alignItems = 'center';
	bubble.style.justifyContent = 'center';
	bubble.style.position = 'relative';
	bubble.style.boxShadow = '0 2px 4px rgba(0,0,0,0.1)';

	// 创建指向三角形的容器
	const pointerWrapper = document.createElement('div');
	pointerWrapper.style.position = 'absolute';
	pointerWrapper.style.bottom = '-8px';
	pointerWrapper.style.left = '50%';
	pointerWrapper.style.transform = 'translateX(-50%)';
	pointerWrapper.style.width = '8px';
	pointerWrapper.style.height = '8px';
	pointerWrapper.style.overflow = 'hidden';

	// 创建指向三角形（使用旋转的正方形实现，这样可以保持边框效果）
	const pointer = document.createElement('div');
	pointer.style.width = '8px';
	pointer.style.height = '8px';
	pointer.style.background = '#1890ff';
	pointer.style.border = '2px solid #FFFFFF';
	pointer.style.position = 'absolute';
	pointer.style.top = '-4px';
	pointer.style.left = '0';
	pointer.style.transform = 'rotate(45deg)';

	// 创建数量显示
	const countText = document.createElement('div');
	countText.style.color = '#fff';
	countText.style.fontSize = `${Math.min(13 + clusterCount * 0.2, 18)}px`;
	countText.style.fontWeight = '500';
	countText.textContent = clusterCount;

	pointerWrapper.appendChild(pointer);
	bubble.appendChild(countText);
	bubble.appendChild(pointerWrapper);
	div.appendChild(bubble);

	// 设置偏移量，使气泡中心对准坐标点
	context.marker.setOffset(new window.AMap.Pixel(-size / 2, -(size / 2 + 6))); // 考虑指向三角形的高度
	context.marker.setContent(div);
}
function _renderMarker(context: any) {
	const content = document.createElement('img');
	content.src = context.data[0].icon;
	content.style.height = '40px';
	content.style.width = '40px';

	context.marker.setOffset(new window.AMap.Pixel(-57, -57));
	context.marker.setContent(content);
	context.marker.on('click', () => markerClick(context.data[0]));
}

/* ------------------ 信息窗体 ------------------------- */
let InfoWindow: any;
var indexTxt = 0;
const imgItem = ref({});
function markerClick(data: any) {
	let title = '';
	let bgColor = '';
	let subTitle = '';
	let element = '';
	imgItem.value = data;
	if (data.type === EventType.Project) {
		// title = '项目';
		bgColor = '#FF993B';
		element = `<div class="text-[17px] text-[#3e3e3e] leading-none mb-2 flex"><span>${data.hphm}</span> <div class='ml-2 text-[#1890FF]'>${data.emissionType}</div></div>
		<div class="text-xs text-[#979797]">${data.companyName} </div>`;
	}
	if (data.type === EventType.Garbage) {
		title = '视频';
		bgColor = '#9C5038';
		let leftbtn = `<div class='btnClick' onclick='popClick()' v-if='${data.bayonetImageList.length > 0}' class='icon_btn' style='width: 20px;height: 20px;background: #C6C6C6;flex:none;border-radius: 50%;text-align: center;color:#FFFFFF'><</div>
`;
		element = `
		<div class="text-xs"><span class="text-[#979797]">地址：</span>${data.deviceAddress}</div>
		<div  onclick="alert(\'Hello World!\')" class="text-xs text-[#979797]">拍摄时间：<span class="text-[#14BD6C] text-1xl mr-1">${data.bayonetImageList[indexTxt].collectionDate}</span> <span class='text-[#E61614]'>${data.bayonetImageList.length}</span></div>
    <div    class='imgBox mt-2 flex justify-between items-center'>
			${leftbtn}
			<div class='p-1'>

					<a class='imgBoxA' href='${data.bayonetImageList[indexTxt].picPath}' target=“_blank”><img  class='imgBoxImg' style="width: 100%; height: 200px"  src="${data.bayonetImageList[indexTxt].picPath}"/></a>

					</div>

					<div onclick='popClicknext()'  v-if='${data.bayonetImageList.length > 0}' class='icon_btn' style='width: 20px;height: 20px;background: #C6C6C6;flex:none;border-radius: 50%;text-align: center;color:#FFFFFF'>></div>
			</div>


		`;
	}
	if (data.type === EventType.Load) {
		title = '装载点';
		bgColor = 'var(--el-color-primary)';
		element = `<div class="text-xs mb-2"><span class="text-[#979797]">开始装载：</span>${data.startTime}</div>
		<div class="text-xs"><span class="text-[#979797]">结束装载：</span>${data.endTime}</div>
		<div class="text-xs text-[#979797]">重量变化：<span class="text-[#FF543D] text-4xl mr-1">+${data.weight}</span>方</div>`;
	}
	if (data.type === EventType.Unload) {
		title = '卸载点';
		bgColor = '#9C5038';
		element = `<div class="text-xs mb-2"><span class="text-[#979797]">开始装载：</span>${data.startTime}</div>
		<div class="text-xs"><span class="text-[#979797]">结束装载：</span>${data.endTime}</div>
		<div class="text-xs text-[#979797]">重量变化：<span class="text-[#14BD6C] text-4xl mr-1">${data.weight}</span>方</div>`;
	}

	if (data.type === EventType.Stay) {
		title = '停留点';
		bgColor = '#9C5038';
		element = `<div class="text-xs mb-2"><span class="text-[#979797]">开始时间：</span>${data.startTime}</div>
		<div class="text-xs"><span class="text-[#979797]">结束时间：</span>${data.endTime}</div>
		<div class="text-xs text-[#979797]">停留时长：<span class="text-[#14BD6C] text-4xl mr-1">${data.diffSeconds}</span>秒</div>`;
	}
	if (data.type === EventType.Camera) {
		title = '视频';
		bgColor = '#9C5038';
		let leftbtn = `<div class='btnClick' onclick='popClick()' v-if='${data.bayonetImageList.length > 0}' class='icon_btn' style='width: 20px;height: 20px;background: #C6C6C6;flex:none;border-radius: 50%;text-align: center;color:#FFFFFF'><</div>
`;
		element = `
		<div class="text-xs"><span class="text-[#979797]">地址：</span>${data.deviceAddress}</div>
		<div  onclick="alert(\'Hello World!\')" class="text-xs text-[#979797]">拍摄时间：<span class="text-[#14BD6C] text-1xl mr-1">${data.bayonetImageList[indexTxt].collectionDate}</span> <span class='text-[#E61614]'>${data.bayonetImageList.length}</span></div>
    <div    class='imgBox mt-2 flex justify-between items-center'>
			${leftbtn}
			<div class='p-1'>

					<a class='imgBoxA' href='${data.bayonetImageList[indexTxt].picPath}' target=“_blank”><img  class='imgBoxImg' style="width: 100%; height: 200px"  src="${data.bayonetImageList[indexTxt].picPath}"/></a>

					</div>

					<div onclick='popClicknext()'  v-if='${data.bayonetImageList.length > 0}' class='icon_btn' style='width: 20px;height: 20px;background: #C6C6C6;flex:none;border-radius: 50%;text-align: center;color:#FFFFFF'>></div>
			</div>


		`;
	}

	// element.appendChild(titleElepc);
	if (!InfoWindow) {
		InfoWindow = new window.AMap.InfoWindow({
			isCustom: true, //使用自定义窗体
			content: _renderInfoWindow(title, bgColor, element, subTitle),
			offset: new window.AMap.Pixel(-30, -50),
		});
	}
	InfoWindow.setContent(_renderInfoWindow(title, bgColor, element, subTitle));
	InfoWindow.open(map, [data.lnglat.lng, data.lnglat.lat]);

	map.setCenter([data.lnglat.lng, data.lnglat.lat]);
}

// function createCarousel(data: any) {
// 	const carouselHtml = `<div class="text-xs"><span class="text-[#979797]">地址：</span>${data.deviceAddress}</div>
// 	<div id="carousel" style="position: relative;">
//         ${data.images
// 					.map(
// 						(src, index) => `
//           <img style="position: absolute; left: ${100 * index}%" src="${src}"/>
//         `
// 					)
// 					.join('')}
//       </div>

// 	`;

// 	return carouselHtml;
// }
function _renderInfoWindow(
	title: string,
	bgColor: string,
	element: string,
	subTitle?: string,
) {
	return `<div class="info-window flex flex-col items-center justify-center relative">
			<div class="info-window-container flex-1 w-full bg-white">

				<div class="info-window-content flex-1 p-3 flex flex-col">${element}</div>
			</div>
			<div class="h-[14px] shrink-0"></div>
			<div class="triangle-icon absolute"></div>
			<div class="triangle-icon absolute" v-if='subTitle'>${subTitle}</div>
		</div>`;
}

function infoWindowclose() {
	InfoWindow?.close();
}

/*------------------ 图列 ----------------------*/
const lengeds = ref([
	{
		name: '摄像头',
		type: EventType.Camera,
		selected: true,
		icon: CameraLengedIcon,
	},

	{
		name: '末端消纳',
		type: EventType.Garbage,
		selected: false,
		icon: GarbageLengedIcon,
	},
	// {
	// 	name: '装货事件',
	// 	type: EventType.Load,
	// 	selected: true,
	// 	icon: LoadLengedIcon,
	// },
	// {
	// 	name: '卸货事件',
	// 	type: EventType.Unload,
	// 	selected: true,
	// 	icon: UnloadLengedIcon,
	// },
	{
		name: '轨迹点',
		type: EventType.Path,
		selected: true,
		icon: MapTrajectory,
	},
	{
		name: '卡口',
		type: EventType.Stay,
		selected: true,
		icon: MapBayonet,
	},
	{
		name: '停靠点',
		type: EventType.Stay,
		selected: true,
		icon: MapStopLen,
	},
	{
		name: '工地',
		type: EventType.Project,
		selected: true,
		icon: MapWorkLen,
	},
	{
		name: '超速点',
		type: EventType.Project,
		selected: true,
		icon: MapSpeed,
	},
]);

function tabsClick(val: string) {
	console.log(val);
	tabPosition.value = val;
	if (val == '车辆分布') {
		markerClusterProject.setData(projectPoint);
		markerClusterGarbage.setData([]);
	} else if (val == '卡口抓拍') {
		markerClusterProject.setData([]);
		garbagePoint = props.pointData.garbage.map((item) => ({
			...item,
			type: EventType.Garbage,
			icon: carIcon,
		}));
		markerClusterGarbage.setData(garbagePoint);
	} else if (val == 'wu') {
		console.log('wu');
		markerClusterProject.setData([]);
		markerClusterGarbage.setData([]);
	}
	infoWindowclose();
}
</script>

<template>
	<div class="vehicle-trajectory relative">
		<div id="kupono-map-container"></div>
		<!-- 车辆切换 -->
		<div class="absolute left-4 top-4 flex items-center flex-col">
			<div
				class="w-[60px] h-[60px] bg-[#E3E3E3] flex items-center flex-col justify-center text-[16px] text-[#AEAEAE]"
				:class="{ tabsActive: tabPosition == '车辆分布' }"
				style="border-radius: 6px"
				@click.stop="tabsClick('车辆分布')"
			>
				<span>车辆</span>
				<span>分布</span>
			</div>
			<div
				class="w-[60px] h-[60px] bg-[#E3E3E3] mt-2 flex items-center flex-col justify-center text-[16px] text-[#aeaeae]"
				:class="{ tabsActive: tabPosition == '卡口抓拍' }"
				@click.stop="tabsClick('卡口抓拍')"
				style="border-radius: 6px"
			>
				<span>卡口</span>
				<span>抓拍</span>
			</div>
		</div>
		<!-- <MapLenged :lengeds="lengeds" @lenged-change="lengedChange" /> -->
		<slot />
	</div>
</template>

<style lang="scss" scoped>
#kupono-map-container {
	height: 100%;
}

:deep(.box) {
	position: relative;
	width: 75px;
	height: 75px;
	display: flex;
	align-items: center;
	justify-content: center;

	.big {
		position: absolute;
		width: 75px;
		height: 75px;
		background: linear-gradient(
			224deg,
			rgba(67, 122, 255, 0.3) 56%,
			#437aff 100%
		);
		opacity: 0.8;
		animation: zoom linear 1.2s infinite;
		animation-delay: 0.1 s;
		border-radius: 75px;
	}

	.small {
		position: absolute;
		width: 47px;
		height: 47px;
		border-radius: 47px;
		background: linear-gradient(
			224deg,
			rgba(67, 122, 255, 0.3) 56%,
			#437aff 100%
		);
		opacity: 0.6;
		animation: zoom linear 1.2s infinite;
	}

	.car {
		width: 16px;
		height: 40px;

		img {
			width: inherit;
			height: inherit;
		}
	}

	@keyframes zoom {
		0% {
			transform: scale(0.5);
			opacity: 0.8;
		}

		100% {
			transform: scale(1);
			opacity: 0.1;
		}
	}
}

:deep(.info-window) {
	width: 218px;

	.info-window-container {
		box-shadow: 0px 4px 18px 0px rgba(0, 0, 0, 0.09);
		border-radius: 4px;
	}

	.info-window-title {
		width: 100%;
		height: 35px;
		border-radius: 4px;
	}

	.triangle-icon {
		border: 10px solid transparent;
		border-top-color: #ffffff;
		bottom: -6px;
	}
}

.mask-btn {
	width: 119px;
	height: 36px;
	background: rgba(0, 0, 0, 0.51);
	border-radius: 4px;
	border: 1px solid #ffffff;
}
.info_box_contant {
	color: red;
}

.icon_btn {
	width: 100px;
	height: 100px;
	background: red;
}

.tabsActive {
	background: #1890ff;
	color: #ffffff;
}
</style>
